package luweiteng.demoForLogin.interceptor;

import luweiteng.demoForLogin.constant.ErrorCode;
import luweiteng.demoForLogin.constant.RedisKey;
import luweiteng.demoForLogin.entity.TestUser;
import luweiteng.demoForLogin.exception.DocUserException;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        实现拦截逻辑

        String token = request.getHeader("token");

        if (StringUtils.isEmpty(token)) {
            throw  new DocUserException(ErrorCode.COMMON_NO_LOGIN);
        }
        String tokenKey = String.format(RedisKey.DOC_USER_TOKEN, token);
        TestUser testUser = (TestUser) redissonClient.getBucket(tokenKey).get();

        if (Objects.isNull(testUser)) {
            throw new DocUserException(ErrorCode.COMMON_USER_NAME_PASSWORD);
        }

        redissonClient.getBucket(tokenKey).expire(10L, TimeUnit.SECONDS);

        return true;
    }
}
